﻿using System;
using System.Collections.Generic;
using System.Text;

namespace csharpcore7_ch4
{
    class StockEventTest1
    {
        static void _Main()
        {
            Stock stock = new Stock("THPW");
            stock.Price = 27.10M;
            //Register with the PriceChanged Event
            stock.priceChanged += stock_PriceChange;
            stock.Price = 31.59M;
        }

        static void stock_PriceChange(object sender, EventArgs e)
        {
            Console.WriteLine("stock pricce 发生了改变");
        }
    }
   

    public class Stock
    {
        string symbol;
        decimal price;

        public Stock(string symbol) { this.symbol = symbol; }

        /// <summary>
        //定义委托类型的事件
        /// </summary>
        public event EventHandler priceChanged;

        /// <summary>
        /// 编写一个protected的虚方法来触发事件
        /// </summary>
        /// <param name="e"></param>
        protected virtual void OnPriceChanged(EventArgs e)
        {
            priceChanged?.Invoke(this, e);
        }
        public decimal Price
        {
            get { return price; }
            set
            {
                if (price == value) return;               
                price = value;
                OnPriceChanged(EventArgs.Empty);
            }
        }
    }
}
